<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Pages extends CI_Controller {

	public function __construct()
	{
		parent::__construct();
        $this->load->model('admin_model','a');
        $this->system = $this->a->get_by_system();
	}
	
	public function login()
	{
		$this->load->library('form_validation');
		$this->form_validation->set_rules('username', '企业账号', 'trim|required');
		$this->form_validation->set_rules('password', '登陆密码', 'required');

		if ($this->form_validation->run() == FALSE)
		{
			$this->load->view('pages/login',array('system'=>$this->system));
		}
		else
		{
			$username = trim($this->input->post("username"));
			$password = $this->input->post("password");
			
			if($this->do_login($username,$password))
			{
				redirect("main/index");
			}else{
				$this->load->view('pages/login',array("msg"=>"用户名或密码错误。",'system'=>$this->system));
			}
		}
	}
//支付回调
    public function notify(){
	    $this->load->model('api_model');
        $xml = file_get_contents("php://input");
        libxml_disable_entity_loader(true);
        $array= json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
        if('SUCCESS'==$array['return_code']) {
                $data['openid'] = $array['openid'];
                $data['out_trade_no'] = $array['out_trade_no'];
                $data['time_end'] = $array['time_end'];
                $data['transaction_id'] = $array['transaction_id'];
                $data['total_fee'] = $array['total_fee'];
                $data['attach'] = json_decode($array['attach'],true)['call_id'];

                $da['sr_callenge'] = json_decode($array['attach'],true)['call_id'];
                $da['sr_user'] = $array['openid'];
                $da['sr_pay'] = $array['total_fee']/100;
                $da['sr_pay_time'] = time();
                $da['sr_time'] = date("Y-m-d",strtotime('1 day'));
                $da['sr_is_close'] = 0;
                $da['sr_formid'] = json_decode($array['attach'],true)['sr_formid'];

                $query = $this->api_model->insert_record($data);//写入
                if($query){
                    $this->api_model->create_sign_record($da);
                    $this->api_model->sign_update_call_status(json_decode($array['attach'],true)['call_id'],$array['openid']);
                    ob_clean();
                    $return = '<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>';
                    echo $return;
                }
        }
    }


	public function do_login($username,$password)
	{
		$this->load->model("admin_model");
		$user_data = $this->admin_model->get_by_username(trim($username));
		
		if(!empty($user_data) && password_verify($password,$user_data["adm_password"]))
		{
			$user_data["login"] = true;
			$this->session->set_userdata($user_data);
			return true;
		}else{
			return false;
		}
	}
	
	public function logout()
	{
		$this->session->unset_userdata("login");
		redirect('pages/login');
	}
	
	//结算
	public function get_result(){
		$this->load->model("activities_model");
		$activities = $this->activities_model->get_all();
		
		$this->load->library('utils');
		for($i=0;$i<count($activities);$i++){
			$a = $activities[$i];
		
			$a["act_status"] = $this->utils->get_activity_status($a);
			
			if(!empty($a["act_result"]) || $a["act_status"]!=2  )
			{
				continue;
			}
			
			$data = json_decode(file_get_contents("https://box.maoyan.com/promovie/api/box/second.json?beginDate=".date ("Ymd",strtotime($a["act_date"]))),true);
			
			if($data["success"])
			{
				$this->load->library("wxapplet");
				$movies = $data["data"]["list"];
				foreach($movies as $m)
				{
					if($m["movieId"] == $a["act_data_url"])
					{
						$n = intval($m["boxInfo"]);
						$this->activities_model->update($a["act_id"],array("act_result"=>$n));
						
						//更新中奖用户信息
						$this->load->model("guesses_model");
						$guess_rank_list = $this->guesses_model->get_rank_list($a["act_id"],$n);
						
						$last_offset = -1;
						$rank = 0;
						for($i=0;$i<count($guess_rank_list);$i++)
						{
							if($guess_rank_list[$i]["offset"] != $last_offset)
							{
								$rank++;
							}
							$iswin = $rank<=$a["act_win_count"];
							$wincode = $iswin?mt_rand(111111,999999):"";
							$this->guesses_model->update($guess_rank_list[$i]["gus_id"],array(
							"gus_rank"=>$rank,
							"gus_status"=>$iswin?1:2,
							"gus_notify"=>$iswin?1:0,
							"gus_code"=>$wincode));
							
							$last_offset = $guess_rank_list[$i]["offset"];
							
							//推送通知用户
							if($guess_rank_list[$i]["gus_bot"] == 0)
							{
								$template_id = "eANkPmjy_czJ7X8iAQ8lGFgzP-n4mjaGTgNIzr-FtR4";
								$page = "pages/index/index?act_id=".$guess_rank_list[$i]["gus_activity"];
								$message = array(
									"keyword1"=>array("value"=>"票房预言家"),//彩种名称
									"keyword2"=>array("value"=>$a["act_date"]),//开奖时间
									"keyword3"=>array("value"=>$a["act_movie"]." 当日票房"),//开奖期数
									"keyword4"=>array("value"=>$n ." 万")//开奖结果
								);
								$color="#d23d3b";
								$emphasis_keyword = "keyword4.DATA";
								$result = $this->wxapplet->send_template_message($guess_rank_list[$i]["gus_user"],$template_id,$page,$guess_rank_list[$i]["gus_formid"],$message,$color,$emphasis_keyword);
								var_dump($result);
							}
						}
					}
				}
			}
			break;
		}
	}
    
	private function parse($sbi)
	{
		$word = mb_substr($sbi,-1,1);
		$number = mb_substr($sbi,0,mb_strlen($sbi)-1);

		if($word == "万")
			return intval($number);
		else if($word == "亿")
			return $number*10000;
	}
	
	public function get_yesterday(){

		$this->load->model("activities_model");
		$activities = $this->activities_model->get_all();
		
		for($i=0;$i<count($activities);$i++){
			$a = $activities[$i];
			
			if(!empty($a["act_yesterday"]) || strtotime($a["act_date"]) > time())
			{
				continue;
			}
			
			echo "https://box.maoyan.com/promovie/api/box/second.json?beginDate=".date ("Ymd",strtotime($a["act_date"])-10);
			$data = json_decode(file_get_contents("https://box.maoyan.com/promovie/api/box/second.json?beginDate=".date ("Ymd",strtotime($a["act_date"])-10)),true);
			
			$flag = true;
			if($data["success"])
			{
				$movies = $data["data"]["list"];
				foreach($movies as $m)
				{
					if($m["movieId"] == $a["act_data_url"])
					{
						//$n = $this->parse($m["sumBoxInfo"]);
						$n = intval($m["boxInfo"]);
						$this->activities_model->update($a["act_id"],array("act_yesterday"=>$n));
						$flag = false;
						break;
					}
				}
				if($flag)
				{
					$this->activities_model->update($a["act_id"],array("act_yesterday"=>-1));
				}
			}
			break;
		}
	
	}
	
	public function robot(){
		$this->load->model("activities_model");
		$activities = $this->activities_model->get_all();
		
		$this->load->library('utils');
		for($i=0;$i<count($activities);$i++){
			$a = $activities[$i];
			
			$a["act_status"] = $this->utils->get_activity_status($a);
			
			if($a["act_status"]==1 &&  mt_rand(1,$a["act_bot_freq"])==1)
			{
				//插入一条记录
				$this->load->model("users_model");
				
				while(true){
					$bot = $this->users_model->get_robot();
					$header = get_headers ($bot["avatarUrl"]);
					var_dump($header);
					if(in_array("X-ErrNo: -6101",$header))
					{
						$this->users_model->delete($bot["openid"]);
					}else{
						break;
					}
				}
				
				
				if($a["act_yesterday"]==0||$a["act_yesterday"]==-1)
				{
					$gn  = mt_rand(1000,9999);
				}else{
					$gn  = mt_rand($a["act_yesterday"]+10,intval($a["act_yesterday"]*1.5));
				}
				$data = array(
					"gus_user"=>$bot["openid"],
					"gus_number"=>$gn,
					"gus_activity"=>$a["act_id"] ,
					"gus_status"=> 0 , 
					"gus_bot"=> 1
				);
				
				$this->load->model("guesses_model");
				$bot = $this->guesses_model->insert($data);
				
				$this->load->model("activities_model");
				$this->activities_model->update($a["act_id"] ,array("act_count"=>$a["act_count"]+1));
			}
		}
	}
	public function tick(){
		$this->get_yesterday();
		$this->robot();
		
		// 结算
		
		
		// 发推
		
	}

    public function get_util()
    {
        $this->load->dbutil();
        $backup = $this->dbutil->backup();
        $this->load->helper('file');
        write_file('/var/www/mybackup.gz', $backup);
        $this->load->helper('download');
        force_download('p021.gz', $backup);
    }

	public function amountSettlement(){//结算调用
        if(strtotime($this->system['sys_over_time'])+1800 <time() && time() < (strtotime($this->system['sys_over_time'])+2400) && $this->a->today_close_call()){
            $surplus = 0;
            $userMoney = 0;
            $this->load->library('wxapplet');
            $callenge = $this->a->amount_settlement();//查看当天打卡记录
            $notuser = $this->a->get_no_day_sign($callenge['call_id']);//未参加打卡人员
            if(0==$callenge['call_num'] || !$callenge){
                $this->a->update_call($surplus,$userMoney,$callenge['call_id']);
                return false;
            }

            if(0==$callenge['call_sign_num']){
                $surplus = $callenge['call_money'];
                $this->a->update_call($surplus,$userMoney,$callenge['call_id']);
                $this->not_loser($notuser,$callenge['call_money']);
                return false;
            }

            $user = $this->a->get_the_day_sign($callenge['call_id']);//成功打卡人员
            //全额打卡
            if ($callenge['call_num'] == $callenge['call_sign_num']) {
                $userMoney = $callenge['call_money'];
                foreach($user as $u){
                    $this->a->update_user(1,$u['sr_user'],$callenge['call_id']);
                    $keyword = "恭喜您成功打卡！今日得到金额1元。今日早起打卡，共".$callenge['call_num']."人参与，成功打卡".$callenge['call_num']."人，瓜分到最高金额".$callenge['call_num']."元，请再接再厉！";
                    $this->wx_template($u['sr_user'],$u['sr_formid'],$keyword);
                }
            } else {

                define('MIN',1);
                $money = $callenge['call_money'];
                $wx_percent= ceil($money * $this->system['sys_wx_percent']/10)/100;//微信手续费
                $sys_percent= ceil($money * $this->system['sys_percent']/10)/100;//平台扣除

                $lose_money = ($callenge['call_num']-$callenge['call_sign_num'])*1;//失败钱

                if($wx_percent>$lose_money || $sys_percent>($lose_money-$wx_percent)){//不足扣
//打卡人每人1
                    $userMoney = $callenge['call_sign_num'];
                    $surplus = $callenge['call_money']->$callenge['call_sign_num'];//剩余钱数
                    foreach($user as $u){
                        $this->a->update_user(1,$u['sr_user'],$callenge['call_id']);
                        $keyword = "恭喜您成功打卡！今日得到金额1元。今日早起打卡，共".$callenge['call_num']."人参与，成功打卡".$callenge['call_sign_num']."人，请再接再厉！";
                        $this->wx_template($u['sr_user'],$u['sr_formid'],$keyword);
                    }

                }else{//足扣
//1.多
                    $surplus = $wx_percent+$sys_percent;//扣除金额
                    $size = $callenge['call_sign_num'];
                    $shuffleoney =$lose_money-$surplus;
                    $userMoney = $shuffleoney+$size;
                    for($i=0;$i<$size;$i++){
                        $u[] = $this->jiesuan($shuffleoney,$callenge['call_sign_num']);
                    }
                    $maxMoney = max($u);
                    foreach ($u as $k=>$v){
                        $this->a->update_user($v,$user[$k]['sr_user'],$callenge['call_id']);
                        $keyword = "恭喜您成功打卡！今日得到金额".$v."元。今日早起打卡，共".$callenge['call_num']."人参与，成功打卡".$size."人，瓜分到最高金额".$maxMoney."元，请再接再厉！";
                        $this->wx_template($user[$k]['sr_user'],$user[$k]['sr_formid'],$keyword);
                    }

                }

            }


            $this->a->update_call($surplus,$userMoney,$callenge['call_id']);
            $this->not_loser($notuser,$callenge['call_money']);

        }
    }


    private function wx_template($user,$formid,$keyword){//微信模板消息
        $template_id = "J0FUS2FzNGMjGaEbTkLOAobZOGmLlY7U4ZtHY6VTlCE";
        $page = "pages/index/index";
        $message = array(
            "keyword1"=>array("value"=>"早起打卡成功提醒"),//彩种名称
            "keyword2"=>array("value"=>$this->system['sys_over_time']),//开奖时间
            "keyword3"=>array("value"=>$keyword),//开奖期数
        );
        $this->wxapplet->send_template_message($user,$template_id,$page,$formid,$message);
    }
    private function not_loser($user,$call_money){
        foreach($user as $k=>$v){
            $template_id = "J0FUS2FzNGMjGaEbTkLOAobZOGmLlY7U4ZtHY6VTlCE";
            $page = "pages/index/index";
            $message = array(
                "keyword1"=>array("value"=>"早起打卡失败提醒"),//彩种名称
                "keyword2"=>array("value"=>$this->system['sys_over_time']),//开奖时间
                "keyword3"=>array("value"=>"您打卡失败，失去了瓜分".$call_money."元的机会"),//开奖期数
            );
            $this->wxapplet->send_template_message($user[$k]['sr_user'],$template_id,$page,$user[$k]["sr_formid"],$message);
        }
    }

	public function jiesuan(&$remainMoney,&$remainSize){
	    if($remainSize==1){
	        $remainSize--;
	        return round($remainMoney*100)/100;
        }
	    $max = $remainMoney / $remainSize * 2;
	    $money = mt_rand(1,100)/100 * $max;
	    $money = floor($money * 100) /100;
	    $remainSize--;
	    $remainMoney -= $money;
	    return $money+MIN;
    }

    public function createCalleng(){//生成挑战
        if(strtotime('0:01')<time() && time() < strtotime('0:10') && !$this->a->today_create_call()){
            $data['call_time'] = date("Y-m-d", strtotime('+1 day'));
            $data['call_num'] = 0;
            $data['call_money'] = 0;
            $data['call_sign_num'] = 0;
            $data['call_is_close'] = 0;
            $data['call_surplus'] = 0;
            $data['call_user_money'] = 0;
            $query = $this->a->create_calleng($data);

        }
    }


}
